package code12线程;

/**
 * @author 黄衡熙
 * @version 1.0
 */

public class Test05_线程安全问题 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        Thread t1 = new Thread(ticket, "窗口1");
        Thread t2 = new Thread(ticket, "窗口2");
        Thread t3 = new Thread(ticket, "窗口3");
        t1.start();
        t2.start();
        t3.start();
    }

}

class Ticket1 implements Runnable {
    private int num = 100;

//    @Override
//    public void run() {
//        while (true) {
//            synchronized (this) {
//                if (num > 0) {
//                    try {
//                        Thread.sleep(10);
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
//                    }
//                    System.out.println(Thread.currentThread().getName() + "正在出票,票号为:" + num--);
//                }
//            }
//        }
//    }

    @Override
    public void run() {
        while (true) {
            sellTicket();
        }
    }

    public synchronized void sellTicket() {
        if (num > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "正在出票,票号为:" + num--);
        }
    }
}
